/*我们遵循一个原则：如果一个文件导出的是一个类，那么这个文件名就用大写开头。  */
import React, {Component} from 'react';
//引入PropTypes插件
import PropTypes from 'prop-types'

import CommentInput from './CommentInput'
import CommentList from './CommentList'

/*
 新增需求
  1.实现评论本地化存储

*/

class CommentApp extends Component {
  //继承Component要初始化
  constructor() {
    super();
    this.state = {
      comments: []
    };
  }

  //页面加载前获取评论
  componentWillMount() {
    this._loadComments();
  }

  //获取本地评论
  _loadComments() {
    let comments = localStorage.getItem('comments');
    console.log(comments);
    if (comments) {
      comments = JSON.parse(comments);
      this.setState({'comments': comments})
    }
  }

  //保存本地评论
  _saveComments(comments) {
    localStorage.setItem('comments', JSON.stringify(comments))
  }

  // 监听接收从子组件传过来的值
  handleSubmitComment(comment) {
    console.log(comment);
    //将接收来的comment推送到this.state.comments数组中
    this
      .state
      .comments
      .push(comment);
    //调用setState()方法改变状态
    this.setState({comments: this.state.comments})
    //将评论保存到本地存储中
    this._saveComments(this.state.comments);

  }

  render() {
    return (
      <div className='wrapper'>
        <CommentInput
          onSubmit={this
          .handleSubmitComment
          .bind(this)}/>
        <CommentList comments={this.state.comments}/>
      </div>
    )
  }
}

export default CommentApp;